package tcpMiddleware

import (
	"fmt"
	"go_gateway/dao"
	"go_gateway/public"
	"strings"
)

// TCPBlackListMiddleware
// @Description: TCP服务黑名单
// @return func(c *TcpSliceRouterContext)
//
func TCPBlackListMiddleware() func(c *TcpSliceRouterContext) {
	return func(c *TcpSliceRouterContext) {
		// 1.获取服务信息
		serverInterface := c.Get("service")
		if serverInterface == nil {
			c.conn.Write([]byte("get service empty"))
			c.Abort()
			return
		}
		serviceDetail := serverInterface.(*dao.ServiceDetail)

		// 2.获取服务白名单
		whiteIPList := []string{}
		if serviceDetail.AccessControl.WhiteList != "" {
			whiteIPList = strings.Split(serviceDetail.AccessControl.WhiteList, ",")
		}

		// 3.获取服务黑名单
		blackIPList := []string{}
		if serviceDetail.AccessControl.BlackList != "" {
			blackIPList = strings.Split(serviceDetail.AccessControl.BlackList, ",")
		}

		// 4.获取客户端ip
		splits := strings.Split(c.conn.RemoteAddr().String(), ":")
		clientIP := ""
		if len(splits) == 2 {
			clientIP = splits[0]
		}

		// 5.黑名单启用条件 开启验证 白名单为空 黑名单不为空
		if serviceDetail.AccessControl.OpenAuth != 0 && len(whiteIPList) == 0 && len(blackIPList) > 0 {
			if public.InStringSlice(whiteIPList, clientIP) {
				c.conn.Write([]byte(fmt.Sprintf("%s in black ip List", clientIP)))
				c.Abort()
				return
			}
		}
		c.Next()
	}
}
